﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using CHR.Contract.Common;
using Kingdee.BOS;
using Kingdee.BOS.Rpc;

namespace CHR.Contracts
{
    /// <summary>
    /// 应用服务器服务组件创建工厂
    /// </summary>
    public class ServiceFactory
    {
        /// <summary>
        /// 服务接口-实现类 映射关系
        /// </summary>
        public static ServicesContainer _mapServer;

        /// <summary>
        /// 是否已注册标识
        /// </summary>
        private static bool _noRegistered = true;
        
        /// <summary>
        /// 获取指定接口实现类实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public static T GetService<T>(Context ctx)
        {
            if (_noRegistered)
            {
                RegisterService();
            }
            var instance = _mapServer.GetService<T>(typeof(T).AssemblyQualifiedName, ctx.ServerUrl);
            if (instance == null)
            {
                throw new KDException("???", "instance == null");
            }
            return instance;
        }

        /// <summary>
        /// 初始化加载服务
        /// </summary>
        public static void RegisterService()
        {
            _mapServer = new ServicesContainer();

            if (_noRegistered)
            {
                //Common
                _mapServer.Add(typeof(ICommonService), "CHR.App.Core.Common.CommonService,CHR.App.Core");
           
                _noRegistered = false;
            }
        }

        /// <summary>
        /// 销毁服务类实例
        /// </summary>
        /// <param name="service"></param>
        public static void CloseService(Object service)
        {
            IDisposable disposable = service as IDisposable;
            if (disposable != null)
            {
                disposable.Dispose();
            }
        }

        #region 服务获取方法

        #region 公共服务获取
        /// <summary>
        /// 公共服务
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public static ICommonService GetCommonService(Context ctx)
        {
            return GetService<ICommonService>(ctx);
        }
        #endregion

        #endregion
    }
}
